package com.fight.strive.sys.modules.redis.impl;

import com.fight.strive.sys.modules.redis.RedisService;
import com.fight.strive.sys.utils.CollectionUtils;
import com.fight.strive.sys.utils.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class RedisServiceImpl implements RedisService {

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    public void valueSet(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    @Override
    public void valueSet(String key, Object value, long timeout, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    @Override
    public <T> T valueGet(String key, Class<T> clz) {
        try {
            Object value = redisTemplate.opsForValue().get(key);
            return clz.cast(value);
        } catch (Exception e) {
            log.error("从redis中获取值失败");
        }
        return null;
    }

    @Override
    public void valueDelete(String key) {
        redisTemplate.delete(key);
    }

    @Override
    public void hashPut(String key, Object objKey, Object objValue) {
        redisTemplate.opsForHash().put(key, objKey, objValue);
    }

    @Override
    public <T> T hashGet(String key, Object objKey, Class<T> clz) {
        try {
            Object obj = redisTemplate.opsForHash().get(key, objKey);
            return clz.cast(obj);
        } catch (Exception e) {
            log.error("从Redis中获取数据{}:{}失败", key, objKey);
        }
        return null;
    }

    @Override
    public <T> List<T> hashGetList(String key, Object objKey, Class<T> clz) {
        try {
            Object obj = redisTemplate.opsForHash().get(key, objKey);
            if (ObjectUtils.notNull(obj)) {
                if (obj instanceof List) {
                    List<?> list = (List<?>) obj;
                    if (CollectionUtils.isNotEmpty(list)) {
                        List<T> list_T = new ArrayList<>();
                        for (Object o : list) {
                            list_T.add(clz.cast(o));
                        }
                        return list_T;
                    }
                }
            }
            return null;
        } catch (Exception e) {
            log.error("从Redis中获取数据{}:{}失败", key, objKey);
        }
        return null;
    }

    @Override
    public void hashDelete(String key, Object... objKey) {
        redisTemplate.opsForHash().delete(key, objKey);
    }
}
